import mitt, { type Emitter, type Handler } from 'mitt';

type EventType = string;
type EventPayload = any;

// 统一的事件处理器
type EventHandler = Handler<EventPayload>;

// 事件总线实例管理
class EventBusManager {
  private static instance: EventBusManager;
  private globalBus: Emitter<Record<EventType, EventPayload>>;
  private moduleBuses: Map<string, Emitter<Record<EventType, EventPayload>>>;
  
  private constructor() {
    this.globalBus = mitt();
    this.moduleBuses = new Map();
  }
  
  public static getInstance(): EventBusManager {
    if (!EventBusManager.instance) {
      EventBusManager.instance = new EventBusManager();
    }
    return EventBusManager.instance;
  }
  
  // 获取全局总线
  public getGlobalBus() {
    return this.globalBus;
  }
  
  // 获取模块总线（修复了每次新建的问题）
  public getModuleBus(moduleId: string) {
    if (!this.moduleBuses.has(moduleId)) {
      const bus = mitt();
      this.moduleBuses.set(moduleId, bus);
      
      // 开发调试
      if (import.meta.env.DEV) {
        (window as any)[`${moduleId}Bus`] = bus;
      }
    }
    return this.moduleBuses.get(moduleId)!;
  }
  
  // 移除模块总线
  public removeModuleBus(moduleId: string) {
    const bus = this.moduleBuses.get(moduleId);
    if (bus) {
      bus.all.clear();
      this.moduleBuses.delete(moduleId);
    }
  }
}

// 创建单例管理器
const eventManager = EventBusManager.getInstance();

// 封装易用的API接口
export const eventBus = {
  // 全局事件
  global: {
    on(event: EventType, handler: EventHandler) {
      eventManager.getGlobalBus().on(event, handler);
    },
    emit(event: EventType, payload?: EventPayload) {
      eventManager.getGlobalBus().emit(event, payload);
    },
    off(event: EventType, handler: EventHandler) {
      eventManager.getGlobalBus().off(event, handler);
    }
  },
  
  // 模块事件
  module(moduleId: string) {
    return {
      on(event: EventType, handler: EventHandler) {
        eventManager.getModuleBus(moduleId).on(event, handler);
      },
      emit(event: EventType, payload?: EventPayload) {
        eventManager.getModuleBus(moduleId).emit(event, payload);
      },
      off(event: EventType, handler: EventHandler) {
        eventManager.getModuleBus(moduleId).off(event, handler);
      }
    };
  },

};

export const globalBus = eventBus.global;
export const getModuleBus = (moduleId: string) => eventBus.module(moduleId);